package node;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.RemoteException;

public class RmiServerNodeStorage implements NodeStorage{
	
	private RmiNodeStorage server;
	Registry registry;
		
	public RmiServerNodeStorage (NodeStorage nodeStorage, String name, int port){
	
		try {
				        	        
			server = new RmiNodeStorageServer(nodeStorage);
			registry = LocateRegistry.createRegistry(port);
			registry.rebind(name, server);
			System.out.println("Server succefully register:" + name + ":" + port);
		} catch (Exception e) {
			System.out.println("Server registering error!" + e.getMessage());
			e.printStackTrace();
		}	
	}
	
	public Node read() throws NodeStorageException{
		try {
			return server.read();
		} catch (RemoteException e){
//			System.out.println("Error during reading the node!" + e.getMessage());
//			e.printStackTrace();
			
			throw new NodeStorageException("3rd:Failed to read node due to RMI server error", e);

		}
	}

	public void store(Node node) throws NodeStorageException{
		try {
			server.store(node);
		} catch (RemoteException e){
//			System.out.println("Error during saving the node!" + e.getMessage());
//			e.printStackTrace();
			
			throw new NodeStorageException("Failed to store node due to RMI server error", e);

		}
	}
	
	
	public static void main(String[] args) throws NodeStorageException {
		
		NodeStorage xml = new XmlNodeStorage();
		RmiServerNodeStorage rmiServer = new RmiServerNodeStorage(xml, "NodeStorage", 1099);
		
	}
		
}

